module.exports = app =>{
  const express = require("express")
  const jwt = require('jsonwebtoken')
  const AdminUser = require('../../models/AdminUser')
  const CustomUser = require('../../models/CustomUser')
  const Flight = require('../../models/Flight')
  const Buy = require('../../models/Buy')
  const ShowData = require('../../models/ShowData')
  const ShowMoney = require('../../models/ShowMoney')
  const Article = require('../../models/Article')
  const assert = require('http-assert')
  const router = express.Router({
    mergeParams:true
  })
  //查询接口
  router.post('/',async(req,res)=>{
    const {start_position,end_position,value,way} = req.body
    console.log(value)
    var today = new Date()
    //3天内
    var day3 = new Date()
    day3.setTime(day3.getTime()+24*3*60*60*1000);
    //7天内
    var day7 = new Date()
    day7.setTime(day7.getTime()+24*7*60*60*1000);
    console.log('today'+today)
    // const date1 = today.getMonth()+1+'-'+today.getDate()
    // const date2 = today.getMonth()+1+'-'+(today.getDate()+1)
    const iso_date = today.toISOString()
    const iso_date_3 = day3.toISOString()
    const iso_date_7 = day7.toISOString()
    // console.log(date1.toString())
    // console.log(date2.toString())
    console.log(iso_date.toString())
    console.log(iso_date_3.toString())
    console.log(iso_date_7.toString())
    let model
    if(value==='选项3'){
      if(way === '往返'){
        model = await req.Model.find({$or:[{start_position,end_position,start_date:{$gte:iso_date}},{start_position:end_position,end_position:start_position,start_date:{$gte:iso_date}}]})
      }else if(way === '单程'){
        model = await req.Model.find({start_position,end_position,start_date:{$gte:iso_date}})
      }else if(way === '接续'){
        model = await req.Model.find({$or:[{start_position,start_date:{$gte:iso_date}},{end_position,start_date:{$gte:iso_date}}]})
      }
    }
    else if(value==='选项2'){
      // const start_date_simple1=date2.toString()
      if(way === '往返'){
      model = await req.Model.find({$or:[{start_position,end_position,start_date:{$gte:iso_date,$lte:iso_date_3}},{start_position:end_position,end_position:start_position,start_date:{$gte:iso_date,$lte:iso_date_3}}]})
      }else if(way === '单程'){
        model = await req.Model.find({start_position,end_position,start_date:{$gte:iso_date,$lte:iso_date_3}})
      }else if(way === '接续'){
        model = await req.Model.find({$or:[{start_position,start_date:{$gte:iso_date,$lte:iso_date_3}},{end_position,start_date:{$gte:iso_date,$lte:iso_date_3}}]})
      }
    }else{
      // const start_date_simple1=date1.toString()
      if(way === '往返'){
        model = await req.Model.find({$or:[{start_position,end_position,start_date:{$gte:iso_date,$lte:iso_date_7}},{start_position:end_position,end_position:start_position,start_date:{$gte:iso_date,$lte:iso_date_7}}]})
        }else if(way === '单程'){
          model = await req.Model.find({start_position,end_position,start_date:{$gte:iso_date,$lte:iso_date_7}})
        }else if(way === '接续'){
          model = await req.Model.find({$or:[{start_position,start_date:{$gte:iso_date,$lte:iso_date_7}},{end_position,start_date:{$gte:iso_date,$lte:iso_date_7}}]})
        }
    }
    //console.log(model)
    res.send(model)
  })
  //
  router.post('/:id',async(req,res)=>{
    // const {start_position,end_position,start_date,end_date} = req.body
    // console.log(start_position)
    // const token = String( req.headers.authorization ||'').split(' ').pop()
    // console.log(req.body)
    // const {id} = jwt.verify(token,app.get('secret'))
    // console.log(id)
    // const model = await CustomUser.findByIdAndUpdate(id,{start_position:"福州"})
    // res.send(model)
  })
  //更新资源(买票)
  router.put('/:id',async(req,res)=>{
    const info = await Flight.findById(req.params.id).select('+start_position+end_position+start_date+end_date+name+start_date_simple+left+money')
    const left = 1
    info.left--
    if(info.left === 0){
      assert(info.left,422,'票已售完')
    }
    const month1 =String( info.start_date_simple.split('-')[0])
    
    console.log(month1)
    //console.log(info.start_position,info.end_position,info.start_date,info.end_date)
    const token = String( req.headers.authorization ||'').split(' ').pop()
    //console.log(req.body)
    const {id} = jwt.verify(token,app.get('secret'))
    console.log(id)
    const values = await ShowData.findOne({name:month1}).select('+name+value+')
    const moneys = await ShowMoney.findOne({name:month1}).select('+name+value+')
    const sales = ++values.value
    const money = info.money + moneys.value
    const model = await CustomUser.findById(id).select('+username')
    const result = await Buy.create({start_position:info.start_position,end_position:info.end_position,start_date:info.start_date,end_date:info.end_date,username:model.username,left:left,name:info.name,start_date_simple:info.start_date_simple,money:info.money})
    await Flight.findByIdAndUpdate(req.params.id,{left:info.left})
    await ShowData.update({name:month1},{value:sales})
    await ShowMoney.update({name:month1},{value:money})
    //await ShowData.create({name:'13',value:0})
    res.send(result)
    })
   
  //删除资源
    router.delete('/:id',async(req,res)=>{
      const info = await req.Model.findById(req.params.id).select('+name+start_date_simple+money+')
      console.log("info的内容"+info)
      const month1 =String( info.start_date_simple.split('-')[0])
      const model1 =await Flight.findOne({name:info.name}).select('+left+_id+')
      const left = ++model1.left
      const values = await ShowData.findOne({name:month1}).select('+name+value+')
      const moneys = await ShowMoney.findOne({name:month1}).select('+name+value+')
      const sales = --values.value
      const money = moneys.value - info.money 
      await req.Model.findByIdAndDelete(req.params.id,req.body)
      res.send({
          success:true
      })
      await Flight.findByIdAndUpdate(model1._id,{left:left})
      await ShowData.update({name:month1},{value:sales})
      await ShowMoney.update({name:month1},{value:money})
    })
  //资源列表
  router.get('/',async(req,res)=>{
    const token = String( req.headers.authorization ||'').split(' ').pop()
    console.log(token)
    if(token === null || token === ''){
      res.send({
        'message':'欢迎您，游客'
      })
    }
    //console.log(req.headers.authorization.split(' ').pop())
    const {id} = jwt.verify(token,app.get('secret'))
    const model = await CustomUser.findById(id).select('+username+id_card+sex+phone+password+')
    console.log(model)
    res.send(model)
    })
  //资源详情
  router.get('/:id',async(req,res)=>{
      const model = await req.Model.findById(req.params.id)
      console.log(model)
      res.send(model)
  }) 
  
  //登录校验中间键
   const authMiddleware = require('../../middleware/auth1')
   const resourceMiddleware = require('../../middleware/resource')
  app.use('/web/api/rest/:resource',resourceMiddleware(),router)
  //authMiddleware(),
 //注册接口
  app.post('/web/api/register',async(req,res)=>{
    const {username,password} = req.body
    const result = await CustomUser.findOne({username})
    assert(!result,422,'用户已存在,请换个名字')
    
    const user = await CustomUser.insertMany({username,password})
    res.send(username)
  })
  app.put('/web/api/save_custom_users',authMiddleware(),async(req,res)=>{
    const token = String( req.headers.authorization ||'').split(' ').pop()
    //console.log(req.body)
    const {id} = jwt.verify(token,app.get('secret'))
    const model = await CustomUser.findByIdAndUpdate(id,req.body)
    res.send(model)
  })
  //获取用户买的票
  app.get('/web/api/user_flights',authMiddleware(),async(req,res)=>{
    //console.log(info.start_position,info.end_position,info.start_date,info.end_date)
    var today = new Date()
    const iso_date = today.toISOString()
    const token = String( req.headers.authorization ||'').split(' ').pop()
    //console.log(req.body)
    const {id} = jwt.verify(token,app.get('secret'))
    //console.log(id)
    const model = await CustomUser.findById(id).select('+username')
    const items = await Buy.find({username:model.username,start_date:{$gte:iso_date}}).limit()
    res.send(items)
  })
  //获取用户过去买的票
  app.get('/web/api/user_flights_history',authMiddleware(),async(req,res)=>{
    //console.log(info.start_position,info.end_position,info.start_date,info.end_date)
    var today = new Date()
    const iso_date = today.toISOString()
    const token = String( req.headers.authorization ||'').split(' ').pop()
    //console.log(req.body)
    const {id} = jwt.verify(token,app.get('secret'))
    //console.log(id)
    const model = await CustomUser.findById(id).select('+username')
    const items = await Buy.find({username:model.username,start_date:{$lte:iso_date}}).limit()
    res.send(items)
  })
  app.get('/web/api/fetch_news_id',async(req,res)=>{
    const _id = req.query.id
    const model = await Article.findById(_id)
    console.log(model.body+'111')
    res.send(model)
  })
  app.get('/web/api/fetch_news',async(req,res)=>{
    const model = await Article.find()
    res.send(model)
  })
  const multer =require('multer')
  const upload = multer({dest:__dirname+'/../../uploads'})
  app.post('/web/api/upload',authMiddleware(),upload.single('file'),async(req,res)=>{
     const file = req.file
     file.url='http://localhost:3000/uploads/'+file.filename
     // 生产环境记得改地址
     //file.url='http://mjubuscoming.cn/uploads/'+file.filename
     res.send(file)
  })


  //用户登录
  app.post('/web/api/c_login',async(req,res)=>{
    const {username,password} = req.body
    //1.根据用户名找用户
    
    const user = await CustomUser.findOne({username}).select('+password')
    assert(user,422,'用户不存在')
    //2.校验密码
    const isValid = require('bcrypt').compareSync(password,user.password)
    assert(isValid,422,'密码错误')
    //3.返回token
    const token = jwt.sign({id:user._id},app.get('secret'))
    res.send({token,username})
   })
//错误处理
  app.use(async(err,req,res,next)=>{
    res.status(err.statusCode||500).send({
      message:err.message
    })
  })
}